package com.haozi.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.haozi.reggie.common.BaseContext;
import com.haozi.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求拦截器
 */
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配符 支持通配符
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //向下转型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取本次请求url
        String requestURI = request.getRequestURI();
        log.info("本次请求URL：{}", requestURI);
        //定义不需要拦截的请求数组
        String[] urls = new String[]{
                "/employee/login",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/user/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //判断是否需要处理
        boolean auth = auth(urls, requestURI);
        if (auth) {
            log.info("本次请求{}不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        //判断PC端是否登录
        if (request.getSession().getAttribute("employee") != null) {
            log.info("用户已登录,用户ID为：{}", request.getSession().getAttribute("employee"));
            Long id = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(id);
            filterChain.doFilter(request, response);
            return;
        }

        //判断移动端是否登录
        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登录,用户ID为：{}", request.getSession().getAttribute("user"));
            Long id = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(id);
            filterChain.doFilter(request, response);
            return;
        }

        log.info("用户未登录");
        //未登录 通过输出流方式向客户端页面相应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean auth(String[] urls, String requestUrl) {
        for (String url : urls) {
            if (PATH_MATCHER.match(url, requestUrl)) {
                return true;
            }
        }
        return false;
    }
}
